package com.bjb.vr.monitor.util;

import com.bjb.vr.common.utils.DateTimeUtil;
import com.bjb.vr.monitor.ao.SwAlarmAo;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.List;

/**
 * @description: skywalking服务性能监控报警工具类
 * @author: HuJingBo
 * @time: 2022/3/16 11:48
 */
@Slf4j
public class SwAlarmSender {

    /**
     * 发送钉钉消息
     *
     * @param alarmList
     * @param title
     */
    public static void sendDingDingMsg(List<SwAlarmAo> alarmList, String title) {
        alarmList.stream().forEach(l -> {
            try {
                StringBuilder alarmMsg = new StringBuilder("## ").append(title).append("\n");
                alarmMsg.append("- ScopeId:").append(l.getScopeId()).append("\n")
                        .append("- ScopeName：").append(l.getScope()).append("\n")
                        .append("- Scope实体ID：").append(l.getId0()).append("\n")
                        .append("- 告警服务名称：").append(l.getName()).append("\n")
                        .append("- 告警规则名称：").append(l.getRuleName()).append("\n")
                        .append("- 告警消息内容：").append(l.getAlarmMessage()).append("\n")
                        .append("- 告警时间：").append(DateTimeUtil.timeStampToDateStr(l.getStartTime())).append("\n");
                DingDingUtil.sendMsg(DingDingUtil.PERFORMANCE_ALARM, title, alarmMsg.toString(), null);
                log.info("钉钉告警消息已发送...");
            } catch (Exception e) {
                log.error("钉钉告警消息发送失败,{}", e);
            }
        });
    }

    /**
     * 发送邮件消息--性能监控
     *
     * @param alarmList
     * @param emailUtil
     * @param mailReceivers
     * @param title
     */
    public static void sendEmailMsg(List<SwAlarmAo> alarmList, EmailUtil emailUtil, List<String> mailReceivers, String title) {
        alarmList.stream().forEach(l -> {
            try {
                HashMap<String, Object> params = new HashMap<>();
                params.put("title", title);
                params.put("scopeId", l.getScopeId());
                params.put("scope", l.getScope());
                params.put("id0", l.getId0());
                params.put("name", l.getName());
                params.put("ruleName", l.getRuleName());
                params.put("alarmMessage", l.getAlarmMessage());
                params.put("startTime", DateTimeUtil.timeStampToDateStr(l.getStartTime()));
                emailUtil.sendTemplateMail(mailReceivers.stream().toArray(String[]::new), title, params, "alarmMail.html");
                log.info("告警邮件已发送...");
            } catch (Exception e) {
                log.error("告警邮件发送失败,{}", e);
            }
        });
    }
}
